import 'dart:async';
import 'dart:developer';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/live/ali_live_logic.dart';
import 'package:ball_lion/module/live/live_chat_logic.dart';
import 'package:ball_lion/utils/mode_config.dart';
import 'package:ball_lion/module/match_detail/live/live_chat_view.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/entity/match/match_live_entity.dart';
import 'package:ball_lion/entity/match/zq_match_info_entity.dart';
import 'package:ball_lion/server/api/other_api.dart';
import 'package:ball_lion/server/api/soccer_api.dart';
import 'package:ball_lion/utils/app_config.dart';
import 'package:ball_lion/utils/constant.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/match_detail/match_views_page.dart';
import 'package:ball_lion/module/match_detail/soccer/zq_lineup_view.dart';
import 'package:ball_lion/module/match_detail/soccer/zq_match_data_view.dart';
import 'package:ball_lion/module/match_detail/soccer/zq_match_info_view.dart';
import 'package:ball_lion/module/match_detail/soccer/zq_match_odds_view.dart';
import 'package:ball_lion/module/match_detail/soccer/zq_match_outs_view.dart';
import 'package:ball_lion/module/match_detail/soccer/zq_model_view.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:ball_lion/server/api/live_api.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/module/match_detail/live/live_source_sheet.dart';
import 'package:ball_lion/widgets/player/qs_player_logic.dart';

class ZqMatchDetailLogic extends GetxController
    with GetTickerProviderStateMixin {
  final scrollC = ApmScrollController();
  late int matchId;
  // LqMatchDetailController();
  // bool _loadUrl = true;
  String tabName = '';
  late TabController tabController =
      TabController(vsync: this, length: tabs.length);
  ZqMatchInfoEntity? info;
  bool showTitle = false;
  List<String> tabsClick = [
    Constant.guandian,
    Constant.baoliao,
    Constant.model
  ];
  // List<MatchVideoEntity>? videoList;
  List<String> tabs = [];
  List<Widget> pages = [];
  bool visible = true;
  bool _isPlayVideo = false;
  String _matchLiveInfo = "";
  MatchLiveEntity? _liveInfo;
  List<MatchLiveEntity>? roomList;
  RxDouble opacity = (1.0).obs;
  Timer? timer;

  bool get isPlayVideo => _isPlayVideo;
  String get matchLiveInfo => _matchLiveInfo;
  MatchLiveEntity? get liveInfo => _liveInfo;

  set liveInfo(MatchLiveEntity? value) {
    _liveInfo = value;
    update();
  }

  set matchLiveInfo(String value) {
    _matchLiveInfo = value;
    update();
  }

  set isPlayVideo(bool value) {
    _isPlayVideo = value;
    update();
  }

  @override
  void onInit() async {
    super.onInit();
    matchId = Get.arguments;
    Get.put(QsPlayerLogic(), tag: "$matchId");
    if (Get.parameters['tabName'].hasValue) {
      tabName = Get.parameters['tabName']!;
      update();
    }
    // tabController = TabController(vsync: this, length: tabs.length);
    scrollC.addListener(() {
      double opa = 1 - scrollC.offset / scrollC.position.maxScrollExtent;
      if (opa < 0) {
        opacity.value = 0;
      } else if (opa > 1) {
        opacity.value = 1;
      } else {
        opacity.value = opa;
      }
      final show = scrollC.offset >= scrollC.position.maxScrollExtent - 5;
      if (show != showTitle) {
        showTitle = show;
        update();
      }
    });

    timer = Timer.periodic(const Duration(seconds: 30), (timer) {
      if (!visible) return;
      getData();
    });
  }

  @override
  void onReady() async {
    super.onReady();
    await playLive();
    await getData();
  }

  @override
  void onClose() {
    super.onClose();
    timer?.cancel();
  }

  Future getVideo() async {
    final result =
        await OtherApi.getVideoList(matchId, 1, Get.parameters['roomId']);
    if (result != null) {
      roomList = result;
      update();
    }
  }

  Future playLive() async {
    await getVideo();
    if (roomList == null) {
      return;
    }
    var index = roomList?.indexWhere((element) =>
        element.roomId.hasValue &&
        element.roomId == Get.parameters['roomId'].toInt());
    if (Get.parameters['roomId'].hasValue) {
      if (index == -1 || index == null) {
        index = 0;
        var info =
            await LiveApi.getLiveDetail(Get.parameters['roomId']!.toInt());
        Get.dialog(
            QsDialog.single(info?.status == 2 ? "专家直播已结束" : "主播暂未开始直播，请耐心等待"));
        return;
      }
      await setLiveStream(true, roomInfo: roomList![index]);
    } else if (Get.parameters['hotLive'] == '1') {
      MatchLiveEntity? live;
      for (MatchLiveEntity entity in roomList!) {
        if (entity.roomId == null &&
            entity.playStatus == 1 &&
            entity.vtype != 4) {
          live = entity;
          break;
        }
      }
      if (live == null) {
        for (MatchLiveEntity entity in roomList!) {
          if (entity.roomId != null && entity.playStatus == 1) {
            live = entity;
            break;
          }
        }
      }
      if (live != null) {
        shouldAutoPlay(live);
      }
    } else if (Get.parameters['hotAnimate'] == '1') {
      MatchLiveEntity? live = roomList?.firstWhere((e) => e.vtype == 4);
      if (live != null) {
        shouldAutoPlay(live);
      }
    } else {
      index = roomList?.indexWhere((element) => element.defaultPlay == 1);
      if (index != null && index != -1) {
        MatchLiveEntity live = roomList![index];
        shouldAutoPlay(live);
      }
    }
  }

  Future shouldAutoPlay(MatchLiveEntity? live) async {
    await setLiveStream(true, roomInfo: live);
    try {
      LiveChatLogic chatLogic =
          Get.find<LiveChatLogic>(tag: "${live?.matchId}");
      chatLogic.getRefresh();
    } catch (e) {
      log("");
    }
    try {
      QsPlayerLogic playerLogic =
          Get.find<QsPlayerLogic>(tag: "${live?.matchId}");
      playerLogic.url = live?.url ?? "";
      playerLogic.doRefresh();
    } catch (e) {
      log("");
    }
  }

  Future setLiveStream(bool videoPlay, {MatchLiveEntity? roomInfo}) async {
    try {
      liveInfo = roomInfo;
    } catch (e) {
      log(e.toString());
    }
    // try{
    //   Get.delete<QsPlayerLogic>(tag: "${liveInfo?.roomId}");
    // }catch(e){
    //   log("");
    // }
    // try{
    //   Get.put(QsPlayerLogic(), tag: "${liveInfo?.roomId}");
    // }catch(e){
    //   log("");
    // }
    isPlayVideo = videoPlay;
    updateTabController();
    update();
  }

  Future getData() async {
    final data = await Utils.tryOrNullf(() async {
      final result = await SoccerApi.getZqMatchInfo(matchId);
      final data = ZqMatchInfoEntity.fromJson(result.data['d']);
      return data;
    });
    if (data != null) {
      info = data;
      if (info?.baseInfo?.homeName.hasValue == true &&
          info?.baseInfo?.guestName.hasValue == true) {
        matchLiveInfo =
            "${info?.baseInfo?.homeName ?? ""} VS ${info?.baseInfo?.guestName ?? ""}";
        try {
          Get.find<AliLiveLogic>(tag: "$matchId").matchInfo = matchLiveInfo;
        } catch (e) {
          log(e.toString());
        }
      }
      try {
        updateTabController();
      } catch (e) {
        log(e.toString());
      }
    }
    update();
  }

  updateTabController() {
    if (info == null) {
      return;
    }
    tabs = [];
    pages = [];
    if (liveInfo?.roomId.hasValue ?? false) {
      tabs.add(Constant.zhibojian);
      pages.add(LiveChatView(matchId: matchId));
    }
    if (info?.live == true) {
      tabs.add(Constant.saikuang);
      pages.add(ZqMatchOutsView(info: info, matchId: matchId));
    }
    if (info?.lineup == true) {
      tabs.add(Constant.zhenrong);
      pages.add(const ZqLineupView());
    }
    // if (info?.injure == true) {
    //   tabs.add(Constant.shangjin);
    //   pages.add(const ZqLineupView(isSuspend: true));
    // }
    if (info?.data == true) {
      tabs.add(Constant.shuju);
      pages.add(ZqMatchDataView(matchId: matchId));
    }
    if (ModeConfig.matchTabs) {
      if (info?.plan == true) {
        tabs.add(Constant.guandian);
        pages.add(MatchViewsPage(matchId: matchId));
      }
      if (info?.ai == true && AppConfig.config.showNavigation[2]) {
        tabs.add(Constant.model);
        pages.add(ZqModelView(matchId: matchId));
      }
      if (info?.info == true) {
        tabs.add(Constant.baoliao);
        pages.add(const ZqMatchInfoView());
      }
    }
    if (info?.odds == true &&
        AppConfig.config.showOdds &&
        ModeConfig.matchDetailOdds) {
      tabs.add(Constant.zhishu);
      pages.add(const ZqMatchOddsView());
    }
    tabController.dispose();
    int index = 0;
    if (tabName.isEmpty) {
      if (info?.baseInfo?.video == 1 &&
          roomList?.first.expertId.hasValue == true) {
        index = tabs.indexWhere((e) => e == Constant.zhibojian);
      } else if (info?.state == MatchState.notStart) {
        if (info?.planCnt != 0 && info?.planCnt != null) {
          index = tabs.indexWhere((e) => e == Constant.guandian);
        } else {
          index = tabs.indexWhere((e) => e == Constant.shuju);
        }
      }
    } else {
      index = tabs.indexOf(tabName);
    }
    if (index < 0 || index >= tabs.length) {
      index = 0;
    }
    if (tabsClick.contains(tabs[index])) {
      SpUtils.setMatchClick(tabs[index], "$matchId");
    }
    tabController =
        TabController(initialIndex: index, length: tabs.length, vsync: this);
    tabController.addListener(() {
      tabName = tabs[tabController.index];
      if (tabsClick.contains(tabs[tabController.index])) {
        SpUtils.setMatchClick(tabs[tabController.index], "$matchId");
      }
      update();
    });
  }

  onTapLive([bool isLive = true]) async {
    Utils.onEvent('bsxq_dhzb');
    if (roomList.noValue) {
      await getVideo();
    }
    if (roomList.hasValue) {
      int? index;
      if (isLive) {
        index = await LiveSourceSheet.show(
            liveList:
                roomList?.where((element) => element.vtype != 4).toList() ?? [],
            select: liveInfo?.expertId);
      } else {
        index = roomList?.indexWhere((element) => element.vtype == 4);
      }
      if (index != null) {
        MatchLiveEntity live = roomList![index];
        if (isLive && !live.playStatus.hasValue) {
          // Toast.text("暂未开始直播，请耐心等待");
          // Utils.onEvent(
          //   "match_detail_live_view",params: {"is_on": 0,"id": live.roomId}
          // );
          // return;
        } else if (live.roomId == 0) {
          Utils.onEvent("match_detail_stream_view");
        }
        if (live.vformat == 'URL') {
          launchUrlString(live.url ?? '',
              mode: LaunchMode.externalApplication,
              webViewConfiguration:
                  const WebViewConfiguration(enableDomStorage: false));
        } else {
          if (live.copyright == 0) {
            Utils.onEvent("match_detail_live_view",
                params: {"is_on": 1, "id": live.roomId});
            setLiveStream(true, roomInfo: live);
            try {
              LiveChatLogic chatLogic =
                  Get.find<LiveChatLogic>(tag: "${live.matchId}");
              chatLogic.getRefresh();
            } catch (e) {
              log("");
            }
            try {
              QsPlayerLogic playerLogic =
                  Get.find<QsPlayerLogic>(tag: "${live.matchId}");
              playerLogic.url = live.url ?? "";
              playerLogic.doRefresh();
            } catch (e) {
              log("");
            }
          } else {
            Toast.text('暂无版权，请选择其他直播源');
          }
        }
      }
    }
  }
}
